package com.ucode.springboot.starter.security.handler;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ucode.tool.base.ResponseResult;
import com.ucode.tool.base.ResultCodeEnum;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

/**
 * Spring security权限不足处理类
 * 只有登录后（即接口有传token）接口权限不足才会进入AccessDeniedHandler
 * 如果是未登陆或者会话超时等，不会触发AccessDeniedHandler，而是会直接跳转到登陆页面
 * 注意:如果全局统一异常处理中捕捉了Exception，则这里不会起效，这时需要在全局异常里单独处理本类中处理的异常
 * @author: liliang
 * @date: 2019年12月25日 上午10:56:23
 */
@Component
public class RestfulAccessDeniedHandler implements AccessDeniedHandler {
    
    private static Log log = LogFactory.get(RestfulAccessDeniedHandler.class);
    
    @Autowired
    private ObjectMapper objectMapper;
    
    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException e) throws IOException, ServletException {
        if(log.isDebugEnabled())
            log.error(e,"Spring security权限不足异常处理");
        
        ResponseResult<Object> result = ResponseResult.result(ResultCodeEnum.UNAUTHORIZED.code,ResultCodeEnum.UNAUTHORIZED.message,null);
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        response.setStatus(200);
        response.getWriter().println(objectMapper.writeValueAsString(result));
        response.getWriter().flush();
        
    }
}